package com.sita.cfmoto.drivedata;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;

import com.amap.api.location.CoordinateConverter;
import com.amap.api.location.DPoint;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyTrafficStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.sita.cfmoto.R;
import com.sita.cfmoto.drivedata.rest.RoutePoint;
import com.sita.cfmoto.event.TrackSyncedEvent;
import com.sita.cfmoto.persistence.RouteData;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.ui.activity.ActivityBase;
import com.sita.cfmoto.utils.FileUtils;
import com.sita.cfmoto.utils.L;
import com.sita.cfmoto.utils.NumberUtils;
import com.sita.cfmoto.utils.PersistUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

public class DriveDataHistoryDetailActivity extends ActivityBase implements AMap.OnMapLoadedListener {

    private final String TAG = DriveDataHistoryDetailActivity.class.getSimpleName();
    @Bind(R.id.map)
    MapView mapView;

    @Bind(R.id.data_mileage)
    TextView mileageValue;

    @Bind(R.id.data_average_speed)
    TextView speedValue;

    @Bind(R.id.data_power)
    TextView powerValue;

    private AMap aMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drive_data_history_detail);
        ButterKnife.bind(this);

        mapView.onCreate(savedInstanceState);
        initMap();

        initToolbar(R.string.drive_data);

        if (DriveDataConstants.driveData == null) {
            finish();
        }

//        distanceView.setText(getString(R.string.distance_km, NumberUtils.formatNumber(DriveDataConstants.driveData.distance / 1000f)));
//        speedView.setText(getString(R.string.speed_kmh, NumberUtils.formatNumber(DriveDataConstants.driveData.speed)));
//        energyView.setText(getString(R.string.energy_v, NumberUtils.formatNumber(DriveDataConstants.driveData.soc)));
        mileageValue.setText(NumberUtils.formatNumber(DriveDataConstants.driveData.distance / 1000f));
        speedValue.setText(NumberUtils.formatNumber(DriveDataConstants.driveData.speed));
        powerValue.setText(NumberUtils.formatNumber(DriveDataConstants.driveData.soc));


        EventBus.getDefault().register(this);
    }

    @Override
    public void onMapLoaded() {
        L.i("onMapLoaded() successfully");
        //initFromToMarkerLine();
//        fetchRouteZipfile();
        getRouteData();
    }

    private void getRouteData() {
        String fileUrl = DriveDataConstants.driveData.routefile;
        String trackId = String.valueOf(DriveDataConstants.driveData.id);
        if (hasRouteInDB(trackId)) {
            fetchRouteFromDB(trackId);
        } else {
            fetchRouteZipfile(fileUrl, trackId);
        }
    }

    private void fetchRouteZipfile(String url, String track) {
        new FileUtils.DownloadFileAsync().execute(url, track);
    }

    private boolean hasRouteInDB(String track) {
        List<RouteData> routeDataList = PersistUtils.getRouteDataList(Long.valueOf(track));
        if (routeDataList == null || routeDataList.size() == 0) {
            return false;
        }
        return true;
    }

    private void fetchRouteFromDB(String track) {
        readDataFromDb();
        initFromToMarkerLine();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
            aMap = null;
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_CENTER);
        mUiSettings.setZoomControlsEnabled(true);
        mUiSettings.setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);
        mUiSettings.setMyLocationButtonEnabled(false);
        mUiSettings.setAllGesturesEnabled(true);
        mUiSettings.setCompassEnabled(true);
        aMap.setMyTrafficStyle(new MyTrafficStyle());
        aMap.setMyLocationEnabled(false);
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

        aMap.setOnMapLoadedListener(this);
        aMap.animateCamera(CameraUpdateFactory.zoomTo(10));
    }

    private void initFromToMarkerLine() {

        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        PolylineOptions polylineOptions = new PolylineOptions().width(10).color(GlobalContext.getGlobalContext().getResources()
                .getColor(R.color.app_third_color));
        int size = DriveDataConstants.driveData.routePoints.size();
        for (int i = 0; i < size; i++) {
            RoutePoint point = DriveDataConstants.driveData.routePoints.get(i);
            LatLng latLng = new LatLng(point.getLatitude(), point.getLongitude());
            polylineOptions.add(latLng);
            builder.include(latLng);
            if (i == 0) {
                MarkerOptions markerOptions = new MarkerOptions()
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.location_a))
                        .draggable(false)
                        .position(latLng);
                aMap.addMarker(markerOptions);
            }
            if (i == size - 1) {
                MarkerOptions markerOptions = new MarkerOptions()
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.location_b))
                        .draggable(false)
                        .position(latLng);
                aMap.addMarker(markerOptions);
            }
        }

        aMap.addPolyline(polylineOptions);

        LatLngBounds bounds = builder.build();
        // 移动地图，所有marker自适应显示。LatLngBounds与地图边缘10像素的填充区域
        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
    }

    public void onEventMainThread(TrackSyncedEvent event) {
        Log.d(TAG, "OnEvent FetchVehicleLocEvent");
        readDataFromDb();
        initFromToMarkerLine();
    }

    private void readDataFromDb() {
        //单条路线
        long trackId = DriveDataConstants.driveData.id;
        //获得单条路线中的gps信息点集合
        List<RouteData> routeDataList = PersistUtils.getRouteDataList(trackId);
        if (DriveDataConstants.driveData.routePoints != null) {
            DriveDataConstants.driveData.routePoints.clear();
        } else {
            DriveDataConstants.driveData.routePoints = new ArrayList<>();
        }
        for (int j = 0; j < routeDataList.size(); ++j) {
            try {
                RoutePoint point = new RoutePoint();
                double lat = routeDataList.get(j).getLatitude();
                double lng = routeDataList.get(j).getLongitude();
                DPoint dpoint = new CoordinateConverter(GlobalContext.getGlobalContext())
                        .from(CoordinateConverter.CoordType.GPS)
                        .coord(new DPoint(lat, lng)).convert();
                point.setLatitude(dpoint.getLatitude());
                point.setLongitude(dpoint.getLongitude());
                point.setTime(routeDataList.get(j).getTime());
                DriveDataConstants.driveData.routePoints.add(point);
            } catch (Exception e) {

            } finally {
                continue;
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.finish();
//        startActivity(new Intent(GlobalContext.getGlobalContext(), DriveStatActivity.class));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
//                startActivity(new Intent(GlobalContext.getGlobalContext(), DriveStatActivity.class));
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
